package com.atguigu.flink.chapter08;


import com.atguigu.flink.bean.OrderEvent;
import com.atguigu.flink.util.AtguiguUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

/**
 * @Author lzc
 * @Date 2022/9/8 9:02
 */
public class Flink06_High_Project_Order {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        env
            .readTextFile("input/OrderLog.csv")
            .map(new MapFunction<String, OrderEvent>() {
                @Override
                public OrderEvent map(String line) throws Exception {
                    String[] data = line.split(",");
                    return new OrderEvent(
                        Long.valueOf(data[0]),
                        data[1],
                        data[2],
                        Long.parseLong(data[3]) * 1000  // 把s变成ms
                    );
                }
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<OrderEvent>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((event, ts) -> event.getEventTime())
            )
            .keyBy(OrderEvent::getOrderId)
            .window(EventTimeSessionWindows.withGap(Time.minutes(30)))
            .process(new ProcessWindowFunction<OrderEvent, String, Long, TimeWindow>() {
    
                private ValueState<OrderEvent> createState;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    createState = getRuntimeContext().getState(
                        new ValueStateDescriptor<OrderEvent>("createState", OrderEvent.class));
                }
    
                @Override
                public void process(Long orderId,
                                    Context ctx,
                                    Iterable<OrderEvent> elements,
                                    Collector<String> out) throws Exception {
                    List<OrderEvent> list = AtguiguUtil.toList(elements);
    
                    if (list.size() == 2) {
                        // 证明creare和pay进入了同一个窗口, 正常支付
                        out.collect("订单: " + orderId + " 正常支付...");
                        
                    }else{
                        OrderEvent event = list.get(0);
    
                        if ("create".equals(event.getEventType())) {
                            // 把create存入到状态中
                            createState.update(event);
                        }else{
                            // 判断create是否存在:
                            // 如果存在: 证明超时支付
                            if (createState.value() != null) {
                                out.collect("订单: " + orderId + " 超时支付..., 系统bug, 需要修复");
                            }else{
                                out.collect("订单: " + orderId + " 只有pay没有create..., 系统bug");
                            }
                            
                        }
                    }
                }
            })
            .print();
        
        
        env.execute();
    }
}
/*
1. 按照订单id keyBy

2. 对数据做处理
    create
        如果是create, 把他存入到状态

    pay
        如果是pay, 判断状态中是否有create,
        
        1. 如果没有create, 证明没有create, 只有pay
        2. 如果有create, 判断下pay的时间和creare的时间是否在30分钟内
            如果在就是正常支付

            如果不在就是超时支付

-----------------------
keyBy: oderId

session窗口: gap设置为 30分钟

如果窗口内有2个元素就一定是正常支付

如果是一个元素:
    有可能是create有可能是pay

    1. 如果是create, 把他存入大状态中

    2. 如果是pya, 判断状态中有没有create
        如果有create 就是超时支付

        如果没有create, 只有pay没有create
 */